package Day2025_02_23;

public class MyBlockingQueue {
    public volatile int[] elements;
    public volatile int head;
    public volatile int tail;
    public volatile int size;

    public MyBlockingQueue(int capacity) {
        if (capacity == 0) {
            throw new RuntimeException("队列容量必须大于零");
        }
        elements = new int[capacity];
    }

    public void put (int value) throws InterruptedException {
        synchronized (this) {
            if (size >= elements.length) {
                this.wait();
            }
            elements[tail++] = value;
            size++;
            if (tail == elements.length) {
                tail = 0;
            }
            notifyAll();
        }
    }

    public synchronized int get () throws InterruptedException {
        if (size <= 0) {
            this.wait();
        }
        int value = elements[head++];
        size--;
        if (head == elements.length) {
            head = 0;
        }
        notifyAll();
        return value;
    }
}
